const { ApolloError } = require('apollo-server')
const { sign } = require('../utils')

module.exports = ({ userSchema }) => ({
  // 登陆请求, 通过 User server 的接口获取
  login: {
    resolve (_, { data }, context, info) {
      console.log(context)
      return info.mergeInfo
        .delegateToSchema({
          schema: userSchema,
          operation: 'query',
          fieldName: 'user',
          args: {
            where: data
          },
          context,
          info
        })
        .then(result => {
          console.log(result)
          if (!result || !result.id) {
            throw new ApolloError('can not find user', 'CAN_NOT_FIND_USER')
          }
          return sign({
            id: result.id,
            jwtid: result.upPdAt
          })
            .then(token => {
              return {
                token,
                ...result
              }
            })
            .catch(error => {
              console.log(error)
            })
        })
        .catch(error => {
          console.log(error)
          throw new ApolloError(error, 'FIND_USER_ERROR')
        })
    }
  },
  register: {
    resolve (_, { data }, context, info) {
      return info.mergeInfo
        .delegateToSchema({
          schema: userSchema,
          operation: 'mutation',
          fieldName: 'createUser',
          args: {
            data
          },
          context,
          info
        })
        .then(result => {
          return sign({
            id: result.id,
            jwtid: result.upPdAt
          })
            .then(token => {
              return {
                token,
                ...result
              }
            })
            .catch(error => {
              console.log(error)
            })
        })
        .catch(error => {
          console.log(error)
          throw new ApolloError(error, 'REGISTER_USER_ERROR')
        })
    }
  }
})
